import base from '@/config/baseUrl';
import store from '@/store';
class socket {
	constructor(options) {
		//地址
		this.socketUrl =  base.socketUrl ;
		this.socketStart = false;
		this.monitorSocketError();
		this.monitorSocketClose();
		this.socketReceive();
	}
	init(callback) {
		const userId = uni.getStorageSync('userId')
		console.log('userId ====> ' + userId);
		const _this = this;
		if (base.socketUrl) {
			if(this.socketStart){
				console.log('全局webSocket已经启动了');
				console.log('地址为===>'  + base.socketUrl);
			}else{
				uni.connectSocket({
					url: this.socketUrl + uni.getStorageSync('userId'),
					header:{
						'content-type': 'application/json',
					},
					method: 'GET'
				});
				uni.onSocketOpen((res) => {
					this.socketStart = true;
					callback && callback();
					console.log('全局WebSocket连接已打开！');
				});
				//发送心跳
				// setTimeout(() => {
				// 	_this.getHeartbeat();
				// }, 5000);
			}
		}else{
			console.log('连接失败');
		}
	}
	//Socket给服务器发送消息
	send(data, callback) {
		const _this = this;
		let username = uni.getStorageSync('username')
		console.log(username)
		if (username) {
			data.userUid = username;
		}
		console.log(data);
		uni.sendSocketMessage({
			data: JSON.stringify(data),
			success: () => {
				callback && callback(true);
			},
			fail: () => {
				console.log("发送失败")
			}
		});
	}
	//Socket接收服务器发送过来的消息
	socketReceive() {
		const _this = this;
		uni.onSocketMessage(function(res) {
			// let data = JSON.parse(res.data);
			// let data = JSON.parse(res);
			 console.log('收到服务器内容：', res.data);
			 if(res.data == "1") {
				  uni.$emit("receiveMessage",res.data)
			 }
			_this.acceptMessage && _this.acceptMessage(res.data);
		});
	}
	//关闭Socket
	closeSocket() {
		const _this = this;
		uni.closeSocket();
		_this.socketStart = false;
	}
	//监听Socket关闭
	monitorSocketClose() {
		const _this = this;
		uni.onSocketClose(function(res) {
			console.log('全局WebSocket 已关闭！');
			_this.socketStart = false;
			setTimeout(function() {
				_this.init();
			}, 3000);
		});
	}
	//监听Socket错误
	monitorSocketError() {
		const _this = this;
		uni.onSocketError(function(res) {
			_this.socketStart = false;
			console.log('WebSocket连接打开失败，请检查！');
		});
	}
	//心跳
	getHeartbeat() {
		const _this = this;
		this.send({
			type: "心跳",
			userUid: uni.getStorageSync('username')
		}, (val) => {
			setTimeout(() => {
				if (val) {
					_this.getHeartbeat();
				} else {
					_this.init();
				}
			}, 10000);
		});
	}
};
const mySocket = new socket();
export default mySocket;
